#!/bin/bash
#author:xieziqiang
#email:xie.zi.qiang@outlook.com
# https://www.haproxy.org/
# https://www.lua.org/download.html
HAPROXY_VERSION="3.0.3"
LUA_VERSION="5.4.7"
SRC_PATH="/usr/local/src"
HAPROXY_INSTALL_PATH="/usr/local"
HAPROXY_USER="haproxy"
HAPROXY_WORKDIR="/var/lib/haproxy"
HAPROXY_LOG="/var/log/haproxy.log"
HAPROXY_CFG="haproxy.cfg"


LUA_COMPRESS="lua-${LUA_VERSION}.tar.gz"
HAPROXY_COMPRESS="haproxy-${HAPROXY_VERSION}.tar.gz"


color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

check_user () {
	if ! id $1 &> /dev/null;then
		color "要创建的用户不存在，创建 $1 " 2
		useradd -m -r -s /sbin/nologin -d "$2" "$1"
	else
		color "$1 用户已存在，不再创建." 0
	fi 
}


compile_lua () {
	if [ ! -e ${LUA_COMPRESS} ];then
		color "当前目录下不存在lua压缩包!" 1
		exit
	fi
	apt update && apt -y install gcc make libssl-dev libpcre3-dev zlib1g-dev libreadline-dev libsystemd-dev \
	&& color "已完成依赖软件包的安装" 0 \
	|| { color "依赖软件包安装失败" 1;exit; }
	tar -xf "${LUA_COMPRESS}" -C "${SRC_PATH}"
	cd "${SRC_PATH}/lua-${LUA_VERSION}" || { color "目录不存在.";exit; }
	make && make all install \
	&& color "已完成lua的编译安装" 0 \
	|| { color "lua编译安装失败" 1;exit; }
	cd -  || { color "目录不存在.";exit; }
}
compile_haproxy () {
	if [ ! -e ${HAPROXY_COMPRESS} ];then
		color "当前目录下不存在haproxy压缩包!" 1
		exit
	fi
	tar -xf "${HAPROXY_COMPRESS}" -C "${SRC_PATH}"
	cd "${SRC_PATH}/haproxy-${HAPROXY_VERSION}" || { color "目录不存在.";exit; }
	make  TARGET=linux-glibc USE_PCRE=1 \
USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_PROMEX=1 USE_LUA=1
	make install PREFIX="${HAPROXY_INSTALL_PATH}"
	cd -  || { color "目录不存在.";exit; }
}
config_haproxy () {
	check_user "${HAPROXY_USER}" "${HAPROXY_WORKDIR}"
	cat > "${HAPROXY_WORKDIR}/${HAPROXY_CFG}" <<__EOF__
global
   maxconn 100000
   chroot /var/lib/haproxy
   stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
    #uid 99
    #gid 99
   user haproxy
   group haproxy
   daemon
    #nbproc 4
    #cpu-map 1 0
    #cpu-map 2 1
    #cpu-map 3 2
    #cpu-map 4 3
    #pidfile /var/lib/haproxy/haproxy.pid
   log 127.0.0.1 local2 debug
defaults
   option http-keep-alive
   option forwardfor
   maxconn 100000
   mode http
   timeout connect 300000ms
   timeout client 300000ms
   timeout server 300000ms
listen stats
   mode http
   bind 0.0.0.0:9999
   stats enable
   log global
   stats uri     /haproxy-status
   stats auth   admin:123456
__EOF__

	cat > /etc/systemd/system/haproxy.service <<__EOF__
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target
[Service]
ExecStartPre=haproxy -f ${HAPROXY_WORKDIR}/${HAPROXY_CFG}   -c -q
ExecStart=haproxy -Ws -f ${HAPROXY_WORKDIR}/${HAPROXY_CFG} -p ${HAPROXY_WORKDIR}/haproxy.pid
ExecReload=/bin/kill -USR2 \$MAINPID
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target
__EOF__

	sed -i '/imudp/s/^#//' /etc/rsyslog.conf
    if [ ! -e "${HAPROXY_LOG}" ];then
        touch "${HAPROXY_LOG}"
        chown  syslog:syslog "${HAPROXY_LOG}"
    fi
	if ! grep -q 'haproxy' /etc/rsyslog.d/50-default.conf;then
    echo "local2.*                        ${HAPROXY_LOG}" >> /etc/rsyslog.d/50-default.conf
	fi
	systemctl daemon-reload
	systemctl restart rsyslog
	systemctl enable --now haproxy \
	&& color "haproxy服务启动成功" 0 \
	|| color "haproxy服务启动失败" 1
}

main () {
	compile_lua
	compile_haproxy
	config_haproxy	
}

main

